package com.server.questionbank.snframe.util.JWT;

import org.springframework.beans.factory.annotation.Value;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import jakarta.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

// JWT Token 生成、验证、提取账号
@Component
public class JwtTokenProvider {

    @Value("${jwt.secret}")
    private String jwtSecret;

    @Value("${jwt.expiration}")
    private int jwtExpirationInMs;

    public int getJwtExpirationInMs() {
        return jwtExpirationInMs;
    }

    // 生成 Token
    public String generateToken(String account) {
        HashMap<String, Object> map = new HashMap<>();

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, jwtExpirationInMs); // 确保单位正确

        return JWT.create()
                .withHeader(map)
                .withClaim("Account", account)
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(jwtSecret));
    }

    // 从 Token 获取账号
    public String getAccountFromToken(String token) {
        return JWT.require(Algorithm.HMAC256(jwtSecret))
                .build()
                .verify(token)
                .getClaim("Account")
                .asString();
    }

    // 验证 Token 是否有效
    // 返回值：
    // -1：Token 过期
    //  0：Token 错误或为空
    //  1：Token 正确
    public int validateToken(String token) {
        if (token == null || token.isEmpty()) return 0;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(jwtSecret)).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getExpiresAt().before(new Date()) ? -1 : 1;
        } catch (Exception e) {
            return 0;
        }
    }

    // 提取 Token
    public String extractTokenFromRequest(HttpServletRequest request) {
        String authorizationHeader = request.getHeader("Authorization");
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            return authorizationHeader.substring(7);
        }

        // 补充：支持从 URL 中读取 token
        String tokenFromParam = request.getParameter("token");
        if (tokenFromParam != null && !tokenFromParam.isEmpty()) {
            return tokenFromParam;
        }
        return null;
    }

    // sha256加密
    public static String sha256(String str) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(str.getBytes("UTF-8"));
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            // 处理异常，可以选择抛出自定义异常或返回默认值
            throw new RuntimeException("SHA-256 algorithm not found", e);
        } catch (UnsupportedEncodingException e) {
            // 处理编码异常
            throw new RuntimeException("UTF-8 encoding not supported", e);
        }
    }
}
